<template>
    <text>{{ text }}</text>
</template>
<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onBeforeUnmount,defineProps } from "vue";
import { $func } from "@/utils";
let timeEr: number | undefined;
const props = withDefaults(defineProps<{
    time?: string|number
    endText?: string
}>(), {
    endText: ''
});
const emit = defineEmits(['end']);
const num = ref<number>();
const text = ref<string>('');
watch(() => props.time, (val: number) => {
    num.value = Math.ceil(val);
    nextTick(() => {
        createTimeEr();
    })
})
onMounted(() => {
    num.value = Math.ceil(props.time);
    nextTick(() => {
        createTimeEr();
    })
})
onBeforeUnmount(() => {
    if (timeEr) {
        clearInterval(timeEr);
        timeEr = void (0);
    }
})
const createTimeEr = () => {
    if (num.value === void (0)) { return; }
    if (num.value > 0) {
        if (timeEr) {
            clearInterval(timeEr);
            timeEr = void (0);
        }
        timeEr = setInterval(() => {
            const t = num.value--;
            if (t <= 0) {
                clearInterval(timeEr);
                timeEr = void (0);
                emit('end');
            } else {
                text.value = $func.getTimeText(t);
            }
        }, 1000)
    } else {
        if (timeEr) {
            clearInterval(timeEr);
            timeEr = void (0);
        }
        if (num.value > -3600) {
            timeEr = setInterval(() => {
                const t = Math.abs(num.value--);
                if (t >= 3600) {
                    clearInterval(timeEr);
                    timeEr = void (0);
                } else {
                    text.value = `超时${$func.getTimeText(t)}`;
                }
            }, 1000)
        } else {
            if (props.endText) {
                text.value = props.endText;
            }
        }
    }
}
</script>
<style lang="scss" scoped></style>